<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        padding: 0;
        margin: 0;
        list-style: none;
        /* box-sizing: border-box; */
      }

      .contain_box {
        position: relative;
        width: 720px;
        /* border: 1px solid #000; */
        margin: 0 auto;
      }

      .contain_box .box1,
      .contain_box .box2 {
        position: relative;
        height: 700px;
        /* border: 1px solid #000; */
      }

      img {
        display: block;
        width: 100%;
      }
    </style>
  </head>

  <body>
    <!-- 官网最外元素 -->
    <div class="contain_box">
      <!--  官网内容一 -->
      <div class="box1">
        <p>
          Lorem ipsum dolor, sit amet consectetur adipisicing elit. Similique
          modi reiciendis cum ad optio, facere nihil dolores tempora minus.
          Ullam, quae maxime architecto illum fugiat praesentium reiciendis
          alias omnis nemo.
        </p>
        <img src="" alt="" lazyload="true" />
      </div>
      <!--  官网内容二 -->
      <div class="box2">
        <p>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Incidunt
          dignissimos consectetur illum distinctio eveniet commodi, ab
          accusantium perferendis molestiae laudantium odit laborum nemo
          nesciunt cum maiores? Tempore in aspernatur consectetur. Hic modi,
          exercitationem qui, facere corporis ipsam asperiores nihil labore eius
          sunt voluptatibus cum illum! Nulla atque nihil sint tenetur mollitia
          numquam neque alias, quasi repellendus qui rerum repudiandae eos!
        </p>
        <img src="" alt="" lazyload="true" />
      </div>
    </div>

    <script>
      let dataRes = [
        {
          id: 1,
          imgPath: "./lazyImg/01.jpeg",
        },
        {
          id: 2,
          imgPath: "./lazyImg/02.jpeg",
        },
      ];
      // 模拟请求回来的数据, 图片路径
      function aysnGetImgs() {
        return new Promise((res, rej) => {
          setTimeout(() => {
            res(dataRes);
          }, 500);
        });
      }

      // aysnGetImgs().then((res) => {
      //     res.forEach((item) => {
      //         arr.push(item)
      //     });
      //     console.log(arr);
      // });

      // async function fn() {
      //     // await 是等待promsie 的返回结果
      //     let res = await aysnGetImgs();
      //     res.forEach((item) => {
      //         arr.push(item)
      //     });
      // };
      // fn();
    </script>

    <script>
      window.onload = async () => {
        // 封装每张图片offsetTop函数
        function getElementOffsetTop(el) {
          let elTop = el.offsetTop;
          let elParent = el.offsetParent;
          // 判断是否到达最顶层
          while (elParent != null) {
            // 累加元素的offsetTop, 直到根节点
            elTop += elParent.offsetTop;
            // 重新赋值, offsetParent
            elParent = elParent.offsetParent;
          }
          // 返回处理完毕的offsetTop
          return elTop;
        }

        let arr = [];
        let res = await aysnGetImgs();
        // console.log(res);
        res.forEach((item) => {
          //   console.log(item);
          arr.push(item);
        });
        console.log(arr);

        lazyImgFn();
        // 封装懒加载函数
        function lazyImgFn() {
          // console.log("滚动中...");
          // 记录网页滚动的scrollTop距离
          let domScropTop = document.documentElement.scrollTop;
          // 获取需要懒加载的图片元素
          let lazyImgs = document.querySelectorAll("img[lazyload='true']");

          // 计算图片是否到达可视区域
          // 遍历所有需要懒加载的图片, 目的是获取所有的图片离顶部的距离
          lazyImgs.forEach((el) => {
            if (window.innerHeight + domScropTop >= getElementOffsetTop(el)) {
              let src = arr.splice(0, 1)[0].imgPath;
              console.log(src);

              el.setAttribute("src", src);
              // 将lazyload属性修改为false(判断是否需要进行懒加载)
              el.setAttribute("lazyload", "false");
            }
          });
        }

        // 监听页面滚动事件
        document.addEventListener("scroll", () => {
          lazyImgFn();
        });
      };
    </script>
  </body>
</html>
